﻿using System;
using System.IO;
using System.Resources;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using EnvDTE;
using SPVisualDev.VSAddin.Dialogs;
using SPVisualDev.VSAddin.Services;
using SPVisualDev.Services;

namespace SPVisualDev.VSAddin.Dialogs
{
    internal partial class DialogResourceEditor : Form
    {
        private const string C_NO_RESOURCE_FILE_TEXT = "(no resource file selected)";
        private const string C_NO_RESOURCE_FILE_CULTURE_SELECTED_TEXT = "(no resource culture selected)";

        private ProjectItem m_feature_folder;
        private string m_default_res_file;
        private string m_selected_resource_file;
        private int m_last_selected_culture_index = -1;
        private ProjectItem m_res_file_opened;
        private XmlDataDocument m_res_file_xml_doc = new XmlDataDocument();

        public DialogResourceEditor(ProjectItem FeatureFolder, string DefaultResourceFile, string ResourceName)
        {
            InitializeComponent();

            m_feature_folder = FeatureFolder;
            m_default_res_file = DefaultResourceFile;
            
            this.ResourceString = ResourceName;

            this.Activated += new EventHandler(DialogResourceEditor_Activated);
        }

        private void DialogResourceEditor_Activated(object sender, EventArgs e)
        {
            try
            {
                //To highlight the selected item in list of available cultures.
                this.lvwAvailableCultures.Focus();
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);
            }
        }

        private void lvwAvailableCultures_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (lvwAvailableCultures.SelectedIndices.Count > 0)
                {
                    if (m_last_selected_culture_index == lvwAvailableCultures.SelectedIndices[0])
                        return;

                    RefreshGrid();

                    m_last_selected_culture_index = lvwAvailableCultures.SelectedIndices[0];
                }
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);

                if (lvwAvailableCultures.Items.Count > 0)
                {
                    lvwAvailableCultures.Items[m_last_selected_culture_index].Selected = true;
                    lvwAvailableCultures.Focus();
                }
            }
        }

        public string SelectedResourceFile
        {
            get
            {
                return m_selected_resource_file;
            }
            set
            {
                if (string.Compare(value, Common.C_LOCAL_RESOURCE_IDENTIFIER, true) == 0)
                {
                    lblSelectedResource.Text = "<Feature folder>\\Resources";
                }
                else
                {
                    lblSelectedResource.Text = value;
                }

                m_selected_resource_file = value;
            }
        }

        private bool IsSelectedResourceFileLocal()
        {
            return (string.Compare(m_selected_resource_file, Common.C_LOCAL_RESOURCE_IDENTIFIER, true) == 0);
        }

        private bool IsDefaultResourceFileLocal()
        {
            return (string.Compare(m_default_res_file, Common.C_LOCAL_RESOURCE_IDENTIFIER, true) == 0);
        }

        public string ResourceString
        {
            get;
            set;
        }

        private void dgvGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            try
            {
                foreach (DataGridViewColumn column in dgvGridView.Columns)
                {
                    string name = column.Name;
                    if (name == "name" || name == "comment" || name == "value")
                        column.Visible = true;
                    else
                        column.Visible = false;
                }

                if (m_res_file_opened != null)
                {
                    btnAddNewCulture.Enabled = true;
                    btnCopyTo.Enabled = true;
                    btnDeleteCulture.Enabled = true;
                    btnNewResourceEntry.Enabled = true;

                    dgvGridView.ReadOnly = false;
                    dgvGridView.AllowUserToAddRows = true;
                    dgvGridView.AllowUserToDeleteRows = true;
                }
                else
                {
                    btnAddNewCulture.Enabled = false;
                    btnCopyTo.Enabled = false;
                    btnDeleteCulture.Enabled = false;
                    btnNewResourceEntry.Enabled = false;

                    dgvGridView.ReadOnly = true;
                    dgvGridView.AllowUserToAddRows = false;
                    dgvGridView.AllowUserToDeleteRows = false;
                }
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);
            }
        }

        private void DialogResourceEditor_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (this.DialogResult == DialogResult.OK && this.ResourceString != null)
                {
                    if (dgvGridView.SelectedRows.Count > 1)
                    {
                        MessageBox.Show("You need to select one row only.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        e.Cancel = true;
                        return;
                    }

                    if (dgvGridView.SelectedRows.Count == 0 && dgvGridView.SelectedCells.Count > 0)
                        dgvGridView.Rows[dgvGridView.SelectedCells[0].RowIndex].Selected = true;

                    if (dgvGridView.SelectedRows.Count == 1)
                    {
                        DataRowView row = (DataRowView)dgvGridView.SelectedRows[0].DataBoundItem;

                        if (row == null)
                        {
                            throw new Exception("No valid item selected.");
                        }
                        else
                        {
                            string name = row["name"] as string;

                            if (string.Compare(this.SelectedResourceFile, m_default_res_file, true) == 0)
                            {
                                ResourceString = "$Resources:" + name + ";";
                            }
                            else
                            {
                                ResourceString = "$Resources:" + this.SelectedResourceFile + "," + name + ";";
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("You need to select one row.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        e.Cancel = true;
                        return;
                    }

                }

                try
                {
                    SaveResourceFileChanges();
                }
                catch (Exception ex)
                {
                    if (DialogError.ShowError(ex, "Could not save resource file changes. Do you still want to exit?", true) != DialogResult.OK)
                    {
                        e.Cancel = true;
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);

                e.Cancel = true;
            }
        }

        private void SaveResourceFileChanges()
        {
            if (m_res_file_xml_doc.DataSet != null && m_res_file_opened != null)
            {
                if (!m_res_file_xml_doc.DataSet.Tables.Contains("data"))
                    return;

                bool bHasChanges = false;
                foreach (DataRow row in m_res_file_xml_doc.DataSet.Tables["data"].Rows)
                {
                    if (row.RowState != DataRowState.Unchanged)
                    {
                        bHasChanges = true;
                        break;
                    }
                }


                if (bHasChanges)
                {
                    if (!Connect.S_Resources_Dont_Ask_before_save)
                    {
                        using (DialogYesNoRepeatable dialog = new DialogYesNoRepeatable())
                        {
                            dialog.DialogMessage = "Save changes to resource file '" + m_res_file_opened.Name + "'?";
                            dialog.DefaultButtonSelect = true;
                            dialog.CheckBoxText = "If answering yes, resources will be saved as needed without asking in the future.";

                            DialogResult result = dialog.ShowDialog();

                            Connect.S_Resources_Dont_Ask_before_save = dialog.RepeatAction && (result == DialogResult.Yes);

                            if (result != DialogResult.Yes)
                                return;
                        }
                    }

                    try
                    {
                        if (!Common.CheckOutItemFromSCC(m_res_file_opened))
                            return;

                        string temp_file = Path.GetTempFileName();

                        try
                        {
                            using (StreamWriter sw = new StreamWriter(temp_file))
                            {
                                using (ResXResourceWriter writer = new ResXResourceWriter(sw))
                                {
                                    foreach (DataRow row in m_res_file_xml_doc.DataSet.Tables["data"].Rows)
                                    {
                                        if (row.RowState == DataRowState.Deleted)
                                            continue;

                                        ResXDataNode node = new ResXDataNode(row["Name"].ToString(), row["Value"] as string);

                                        if (dgvGridView.Columns.Contains("Comment"))
                                            node.Comment = row["Comment"] as string;

                                        writer.AddResource(node);
                                    }

                                    writer.Generate();
                                    writer.Close();
                                }

                                sw.Close();
                            }

                            File.Copy(temp_file, Common.GetProjectItemPath(m_res_file_opened), true);
                        }
                        finally
                        {
                            try
                            {
                                if (File.Exists(temp_file))
                                    File.Delete(temp_file);
                            }
                            catch { }
                        }
                    }
                    catch
                    {
                        Connect.S_Resources_Dont_Ask_before_save = false;
                        throw;
                    }
                }

            }
        }

        private void DialogResourceEditor_Load(object sender, EventArgs e)
        {
            this.dgvGridView.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dgvGridView_DataBindingComplete);
            this.lvwAvailableCultures.SelectedIndexChanged += new EventHandler(lvwAvailableCultures_SelectedIndexChanged);

            this.lvwAvailableCultures.MultiSelect = false;
            this.lvwAvailableCultures.HideSelection = false;
            this.lvwAvailableCultures.ListViewItemSorter = new ListViewCultureComparer();

            this.lblSelectedResource.Text = C_NO_RESOURCE_FILE_TEXT;
            this.lblResourceFileName.Text = C_NO_RESOURCE_FILE_CULTURE_SELECTED_TEXT;

            if (!string.IsNullOrEmpty(m_default_res_file))
            {
                this.SelectedResourceFile = m_default_res_file;

                RefreshAvailableCultures();

                /*
                if (lvwAvailableCultures.Items.Count > 0)
                {
                    lvwAvailableCultures.Items[0].Selected = true;
                    lvwAvailableCultures.Refresh();

                    RefreshGrid();
                }
                */
            }

            if (this.ResourceString == null)
            {
                btnOK.Text = "OK";
                btnCancel.Visible = false;
                btnNewResourceEntry.Visible = false;
            }

            this.FormClosing += new FormClosingEventHandler(DialogResourceEditor_FormClosing);

            this.dgvGridView.CellValueChanged += new DataGridViewCellEventHandler(dgvGridView_CellValueChanged);
            this.dgvGridView.RowsRemoved += new DataGridViewRowsRemovedEventHandler(dgvGridView_RowsRemoved);
            this.dgvGridView.MultiSelect = true;
        }

        private void dgvGridView_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
        }

        private void dgvGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void RefreshGrid()
        {
            if (lvwAvailableCultures.SelectedItems.Count == 0)
                return;

            //string selected_resource = m_selected_res_file;

            string res_path = null;
            string culture = "";
            if (lvwAvailableCultures.SelectedItems[0].SubItems[0].Text != "Default")
            {
                culture = "." + lvwAvailableCultures.SelectedItems[0].SubItems[0].Text;
            }

            ProjectItem resource_file_item = null; 
            
            if (this.SelectedResourceFile.ToLower() != "core")
            {
                ProjectItem resources = null;
                try
                {
                    if (IsSelectedResourceFileLocal())
                    {
                        resources = m_feature_folder.ProjectItems.Item("Resources");
                        if (resources.Kind != Constants.vsProjectItemKindPhysicalFolder)
                            resources = null;
                    }
                    else
                    {
                        resources = m_feature_folder.ContainingProject.ProjectItems.Item("12").ProjectItems.Item("Resources");
                    }
                }
                catch { }

                if (resources != null)
                {
                    try
                    {
                        string s = IsSelectedResourceFileLocal() ? "Resources" : this.SelectedResourceFile;
                        resource_file_item = resources.ProjectItems.Item(s + culture + ".resx");
                    }
                    catch { }

                    if (resource_file_item != null)
                    {
                        res_path = Common.GetProjectItemPath(resource_file_item);
                    }
                }

            }
            else if (!Connect.S_Client_Install) //Changed to support client installation
            {
                res_path = SharePointLibrary.GetSharePointInstallPath() + "\\Resources\\core" + culture + ".resx";
            }

            if (!string.IsNullOrEmpty(res_path))
            {
                SaveResourceFileChanges();

                m_res_file_opened = resource_file_item;

                m_res_file_xml_doc = new XmlDataDocument();
                m_res_file_xml_doc.PreserveWhitespace = true;
                m_res_file_xml_doc.DataSet.ReadXml(res_path);
                m_res_file_xml_doc.DataSet.AcceptChanges();

                if (m_res_file_xml_doc.DataSet.Tables.Contains("data"))
                {
                    m_res_file_xml_doc.DataSet.Tables["data"].PrimaryKey = new DataColumn[] { m_res_file_xml_doc.DataSet.Tables["data"].Columns["Name"] };
                    m_res_file_xml_doc.DataSet.EnforceConstraints = true;

                    dgvGridView.DataSource = m_res_file_xml_doc.DataSet.DefaultViewManager;
                    dgvGridView.DataMember = "Data";
                }


                lblResourceFileName.Text = Path.GetFileName(res_path);

            }
            else
            {
                m_res_file_opened = null;
                dgvGridView.DataSource = null;

                lblResourceFileName.Text = C_NO_RESOURCE_FILE_CULTURE_SELECTED_TEXT;
            }


            /*
            if (m_res_file_opened != null)
            {
                lblResourceFileName.Text = m_res_file_opened.Name;
                if (culture == "")
                    lblResourceFileName.Text += " (default)";

            }
            else
            {
                lblResourceFileName.Text = C_NO_RESOURCE_FILE_CULTURE_SELECTED_TEXT;
            }
             */ 
        }

        private void RefreshAvailableCultures()
        {
            string selected = this.SelectedResourceFile;
            if (string.IsNullOrEmpty(selected))
                return;

            string selected_culture = string.Empty;

            if (lvwAvailableCultures.SelectedItems.Count > 0)
                selected_culture = lvwAvailableCultures.SelectedItems[0].SubItems[0].Text;

            lvwAvailableCultures.Items.Clear();

            if (selected.ToLower() == "core" && !Connect.S_Client_Install) //Changed to support client installation
            {
                string res_path = SharePointLibrary.GetSharePointInstallPath() + "\\Resources";
                if (Directory.Exists(res_path))
                {
                    foreach (string file in Directory.GetFiles(res_path))
                    {
                        if (Path.GetExtension(file).ToLower() != ".resx")
                            continue;

                        string file_name = Path.GetFileName(file);
                        if (file_name.ToLower().StartsWith(selected.ToLower() + "."))
                        {
                            string res_file_name = Path.GetFileNameWithoutExtension(file_name);
                            if (res_file_name.LastIndexOf(".") != -1)
                            {
                                string culture = res_file_name.Substring(res_file_name.LastIndexOf(".") + 1);

                                ListViewItem lvItem = new ListViewItem(new string[] { culture, CultureInfo.GetCultureInfo(culture).LCID.ToString(), res_file_name });
                                lvwAvailableCultures.Items.Add(lvItem);
                            }
                        }
                    }
                }
            }
            else
            {
                ProjectItem resources = null;
                try
                {
                    if (IsSelectedResourceFileLocal())
                    {
                        resources = m_feature_folder.ProjectItems.Item("Resources");
                        if (resources.Kind != Constants.vsProjectItemKindPhysicalFolder)
                            resources = null;
                    }
                    else
                    {
                        resources = m_feature_folder.ContainingProject.ProjectItems.Item("12").ProjectItems.Item("Resources");
                    }
                }
                catch { }



                bool isValid = false;
                if (resources != null)
                {
                    try
                    {
                        ProjectItem default_res_file = resources.ProjectItems.Item((IsSelectedResourceFileLocal()) ? "Resources.resx" : this.SelectedResourceFile + ".resx");
                        isValid = true;
                    }
                    catch
                    {
                        isValid = false;
                    }


                    if (isValid)
                    {
                        foreach (ProjectItem item in resources.ProjectItems)
                        {
                            if (!item.Name.ToLower().EndsWith(".resx"))
                                continue;

                            string s = (IsSelectedResourceFileLocal()) ? "Resources" : selected;
                            if (item.Name.ToLower().StartsWith(s.ToLower() + "."))
                            {
                                string res_file_name = Path.GetFileNameWithoutExtension(item.Name);
                                if (res_file_name.LastIndexOf(".") != -1)
                                {
                                    string culture = res_file_name.Substring(res_file_name.LastIndexOf(".") + 1);

                                    ListViewItem lvItem = new ListViewItem(new string[] { culture, CultureInfo.GetCultureInfo(culture).LCID.ToString(), res_file_name });
                                    lvwAvailableCultures.Items.Add(lvItem);
                                }

                            }
                        }
                    }

                }

                if (!isValid)
                {
                    selected = null;
                    selected_culture = null;
                    
                    this.SelectedResourceFile= C_NO_RESOURCE_FILE_TEXT;
                }

            }

            if (!string.IsNullOrEmpty(selected))
            {
                ListViewItem lvItem = new ListViewItem(new string[] { "Default", CultureInfo.InvariantCulture.LCID.ToString(), (IsSelectedResourceFileLocal()) ? "Resources" : selected });
                lvwAvailableCultures.Items.Insert(0, lvItem);
            }

            if (!string.IsNullOrEmpty(selected_culture))
            {
                foreach (ListViewItem item in lvwAvailableCultures.Items)
                {
                    if (string.Compare(item.SubItems[0].Text, selected_culture, true) == 0)
                    {
                        lvwAvailableCultures.Focus();
                        item.Selected = true;
                        break;
                    }
                }
            }

            if (lvwAvailableCultures.SelectedItems.Count == 0 && lvwAvailableCultures.Items.Count > 0)
            {
                lvwAvailableCultures.Focus();
                lvwAvailableCultures.Items[0].Selected = true;
            }
        }

        private void btnChangeResourceFile_Click(object sender, EventArgs e)
        {
            try
            {
                SaveResourceFileChanges();
            }
            catch(Exception ex)
            {
                DialogError.ShowError(ex);
                return;
            }
            
            try
            {

                using (DialogSelectResource dialog = new DialogSelectResource(m_feature_folder, false, this.SelectedResourceFile))
                {
                    DialogResult res = dialog.ShowDialog(this);
                    if (res == DialogResult.OK && !string.IsNullOrEmpty(dialog.ResourceFileName))
                    {
                        this.SelectedResourceFile = dialog.ResourceFileName;

                        RefreshAvailableCultures();
                        dgvGridView.DataSource = null;

                        RefreshGrid();
                    }
                }
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);
            }
        }

        private void btnNewResourceFile_Click(object sender, EventArgs e)
        {
            try
            {
                SaveResourceFileChanges();
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);
                return;
            }

            try
            {
                using (DialogSelectResource dialog = new DialogSelectResource(m_feature_folder, true, this.SelectedResourceFile))
                {
                    DialogResult res = dialog.ShowDialog(this);
                    if (res == DialogResult.OK && !string.IsNullOrEmpty(dialog.ResourceFileName))
                    {
                        this.SelectedResourceFile = dialog.ResourceFileName;

                        RefreshAvailableCultures();

                        RefreshGrid();
                    }
                }
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);
            }
        }

        private void btnNewResourceEntry_Click(object sender, EventArgs e)
        {
            try
            {
                if (m_res_file_xml_doc.DataSet != null && m_res_file_opened != null)
                {
                    if (!m_res_file_xml_doc.DataSet.Tables.Contains("data"))
                        return;

                    if (ResourceHelper.IsResourceString(this.ResourceString))
                    {
                        string s = ResourceHelper.ParseResourceKeyFromRawString(this.ResourceString);

                        if (string.Compare(this.SelectedResourceFile, Common.C_LOCAL_RESOURCE_IDENTIFIER, true) != 0)
                            s = Common.FilterIllegalCharsInFileName(m_feature_folder.Name) + "_" + s;

                        if (!string.IsNullOrEmpty(s))
                        {
                            DataRow row = m_res_file_xml_doc.DataSet.Tables["data"].Rows.Find(s);
                            if (row == null)
                            {
                                m_res_file_xml_doc.DataSet.Tables["data"].Rows.Add(new string[] { s, "" });

                                dgvGridView.ClearSelection();

                                foreach (DataGridViewRow dgvr in dgvGridView.Rows)
                                {
                                    if (dgvr.Cells[0].Value.ToString() == s)
                                    {
                                        dgvr.Selected = true;
                                        break;
                                    }
                                }

                            }
                            else
                            {
                                MessageBox.Show("There is already a default entry.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);
            }
        }

        private void btnAddNewCulture_Click(object sender, EventArgs e)
        {
            try
            {
                SaveResourceFileChanges();
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);
                return;
            }

            try
            {

                CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
                List<CultureInfo> list = new List<CultureInfo>(cultures);

                using (DialogResourceNewCulture dialog = new DialogResourceNewCulture(list))
                {
                    dialog.InfoLabel = "Add new culture for " + this.SelectedResourceFile;

                    DialogResult result = dialog.ShowDialog(this);
                    if (result == DialogResult.OK)
                    {
                        foreach (ListViewItem item in lvwAvailableCultures.Items)
                        {
                            if (string.Compare(item.SubItems[0].Text, dialog.SelectedCulture, true) == 0)
                            {
                                MessageBox.Show("The selected culture is already in the collection.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return;
                            }
                        }

                        NewResourceCulture(dialog.SelectedCulture);
                        CopyResourceFile(string.Empty, dialog.SelectedCulture);

                        RefreshAvailableCultures();
                        SelectCulture(dialog.SelectedCulture);

                    }
                }
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);
            }
        }

        private void btnCopyTo_Click(object sender, EventArgs e)
        {
            try
            {
                if (m_res_file_opened == null)
                {
                    MessageBox.Show("No resource file to copy from.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                List<CultureInfo> list = new List<CultureInfo>();
                foreach (ListViewItem item in lvwAvailableCultures.Items)
                {
                    if (item.SubItems[0].Text == "Default" || item.Selected)
                        continue;

                    list.Add(new CultureInfo(item.SubItems[0].Text));
                }

                if (list.Count == 0)
                {
                    MessageBox.Show("No available cultures to copy to. Copy to the default file is not supported either.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                try
                {
                    SaveResourceFileChanges();
                }
                catch (Exception ex)
                {
                    DialogError.ShowError(ex);
                    return;
                }

                using (DialogResourceNewCulture dialog = new DialogResourceNewCulture(list))
                {
                    dialog.InfoLabel = "Copy " + m_res_file_opened.Name + " to";
                    dialog.AcceptButtonText = "OK";
 
                    DialogResult result = dialog.ShowDialog(this);
                    if (result == DialogResult.OK)
                    {
                        ListViewItem copy_to = null;
                        foreach (ListViewItem item in lvwAvailableCultures.Items)
                        {
                            if (string.Compare(item.SubItems[0].Text, dialog.SelectedCulture, true) == 0)
                            {
                                copy_to = item;
                                break;
                            }
                        }
                        string selected_culture = GetSelectedCulture();

                        if (copy_to == null)
                        {
                            if (MessageBox.Show("The selected culture for this resource is not yet created. Do you want to create one now?", "Prompt", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                NewResourceCulture(dialog.SelectedCulture);
                            }
                            else
                            {
                                return;
                            }
                        }
                        else
                        {
                            string s = selected_culture;
                            if (string.IsNullOrEmpty(s))
                                s = "(default)";
                            if (MessageBox.Show("All resource keys in " + dialog.SelectedCulture + " will be deleted and copied from " + s +". Do you want to continue?", "Prompt", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2) != DialogResult.Yes)
                            {
                                return;
                            }
                        }

                        CopyResourceFile(selected_culture, dialog.SelectedCulture);

                        RefreshAvailableCultures();
                        SelectCulture(dialog.SelectedCulture);


                    }
                }
            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);

                try
                {
                    RefreshAvailableCultures();
                }
                catch { }
            }

        }

        private string GetSelectedCulture()
        {
            if (lvwAvailableCultures.SelectedItems.Count > 0)
            {
                if (lvwAvailableCultures.SelectedItems[0].SubItems[0].Text == "Default")
                    return string.Empty;
                else
                    return lvwAvailableCultures.SelectedItems[0].SubItems[0].Text;
            }
            else
            {
                return null;
            }
        }

        private void SelectCulture(string Culture)
        {
            if (lvwAvailableCultures.SelectedItems.Count > 0)
            {
                foreach (ListViewItem item in lvwAvailableCultures.Items)
                {
                    if (string.Compare(item.SubItems[0].Text, Culture, true) == 0)
                    {
                        item.Selected = true;
                        lvwAvailableCultures.Focus();
                        break;
                    }
                }
            }
        }

        private void NewResourceCulture(string CultureString)
        {
            if (IsSelectedResourceFileLocal())
            {
                Common.AddNewCulture("Resources", CultureString, m_feature_folder.ContainingProject, m_feature_folder);
            }
            else
            {
                Common.AddNewCulture(this.SelectedResourceFile, CultureString, m_feature_folder.ContainingProject, null);
            }
        }

        private void CopyResourceFile(string SourceCulture, string DestinationCulture)
        {
            ProjectItem resources = null;

            string src_res_file_name = IsSelectedResourceFileLocal() ? "Resources" : this.SelectedResourceFile;
            if (!string.IsNullOrEmpty(SourceCulture))
                src_res_file_name += "." + SourceCulture;
            src_res_file_name += ".resx";

            string dest_res_file_name = IsSelectedResourceFileLocal() ? "Resources" : this.SelectedResourceFile;
            if (!string.IsNullOrEmpty(DestinationCulture))
                dest_res_file_name += "." + DestinationCulture;
            dest_res_file_name += ".resx";

            if (IsSelectedResourceFileLocal())
            {
                ProjectItem resource_folder = Common.CreateProjectItemPath(m_feature_folder.ContainingProject, "12\\TEMPLATE\\Features\\" + m_feature_folder.Name + "\\Resources");

                try
                {
                    resources = resource_folder.ProjectItems.Item(dest_res_file_name);
                }
                catch
                {
                    throw new Exception("The destination resource file could not be found.");
                }

            }
            else
            {
                ProjectItem resource_folder = Common.CreateProjectItemPath(m_feature_folder.ContainingProject, "12\\Resources");
                try
                {
                    resources = resource_folder.ProjectItems.Item(dest_res_file_name);
                }
                catch
                {
                    throw new Exception("The destination resource file could not be found.");
                }
            }

            if (resources != null)
            {

                if (!Common.CheckOutItemFromSCC(resources))
                    return;

                string dest_file_path = Common.GetProjectItemPath(resources);
                string temp_file = Path.GetTempFileName();

                try
                {
                    using (StreamWriter sw = new StreamWriter(temp_file))
                    {
                        using (ResXResourceWriter writer = new ResXResourceWriter(sw))
                        {
                            using (ResXResourceReader reader = new ResXResourceReader(Path.GetDirectoryName(dest_file_path) + "\\" + src_res_file_name))
                            {
                                reader.UseResXDataNodes = true;
                                foreach (System.Collections.DictionaryEntry entry in reader)
                                {
                                    string value = string.Empty;

                                    ResXDataNode resx_node = new ResXDataNode(entry.Key.ToString(), value);
                                    writer.AddResource(resx_node);
                                }

                                reader.Close();
                            }

                            writer.Close();
                        }

                        sw.Close();
                    }

                    File.Copy(temp_file, dest_file_path, true);
                }
                finally
                {
                    try
                    {
                        if (File.Exists(temp_file))
                            File.Delete(temp_file);
                    }
                    catch { }
                }

            }
            else
            {
                throw new Exception("The destination resource file could not be found.");
            }

        }

        private void btnDeleteCulture_Click(object sender, EventArgs e)
        {
            try
            {
                if (m_res_file_opened != null)
                {
                    string culture = GetSelectedCulture();

                    if (culture == string.Empty)
                    {
                        string msg = "You can not delete the default resource file from this editor.";
                        MessageBox.Show(msg, "Prompt", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                        
                        /*

                        List<ProjectItem> items_to_delete = new List<ProjectItem>();
                        ProjectItem folder = m_res_file_opened.Collection.Parent as ProjectItem;
                        foreach (ProjectItem item in folder.ProjectItems)
                        {
                            string s = Path.GetFileNameWithoutExtension(item.Name);
                            if (s.ToLower().StartsWith(m_res_file_opened.Name.ToLower() + "."))
                                items_to_delete.Add(item);
                        }

                        foreach (ProjectItem item in items_to_delete)
                            item.Delete();

                        m_res_file_opened.Delete();
                        */
                    }
                    else
                    {
                        string msg = "Do you want to delete the resource file named '" + m_res_file_opened.Name + "'?";
                        if (MessageBox.Show(msg, "Prompt", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2) != DialogResult.OK)
                            return;

                        m_res_file_opened.Delete();
                    }


                    m_res_file_opened = null;
                    lvwAvailableCultures.SelectedItems.Clear();
                    lblResourceFileName.Text = string.Empty;

                    RefreshAvailableCultures();
                }

            }
            catch (Exception ex)
            {
                DialogError.ShowError(ex);
            }
        }


    }

    internal class ListViewCultureComparer : System.Collections.IComparer
    {

        #region IComparer Members

        public int Compare(object x, object y)
        {
            ListViewItem itemX = (ListViewItem)x;
            ListViewItem itemY = (ListViewItem)y;

            int i;
            if (itemX.SubItems[0].Text == "Default")
                i = -1;
            else
                i =string.Compare(itemX.SubItems[0].Text, itemY.SubItems[0].Text);

            return i;
        }

        #endregion
    }
}
